import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { visualizer } from 'rollup-plugin-visualizer'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite';
import { VantResolver } from 'unplugin-vue-components/resolvers';
import postCssPxToRem from 'postcss-pxtorem'
import { resolve } from 'path'
export default defineConfig({
  // 注入全局变量
  define: {
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
  },
  base: './',
  css: {
    postcss: {
      plugins: [
        postCssPxToRem({
          rootValue: 37.5,
          propList: ['*'],
        })
      ]
    },
    preprocessorOptions: {
      scss: {
        javascriptEnabled: true,
        additionalData: '@import "./src/styles/variables.scss";'
      }
    }
  },
  server: {
    host: '10.98.143.86',
    port: 3002,
    open: true,
    proxy: {
      [process.env.VITE_BASE_API]: {
        target: process.env.VITE_BASE_URL,   //接口地址
        changeOrigin: true,
        rewrite: (path) => path.replace(['^' + process.env.VITE_BASE_URL], '')
      },
    }
  },
  plugins: [
    vue(),
    AutoImport({
      resolvers: [VantResolver()],
    }),
    Components({
      resolvers: [VantResolver()],
    }),],
  resolve: {
    // 设置文件./src路径为 @
    alias: [
      {
        find: '@',
        replacement: resolve(__dirname, './src')
      }
    ],
  },
  build: {
    // 打包出口文件
    outDir: 'dist',
    // outDir: 'cashierFrontH5',
    // 打包前先清空原有打包文件
    emptyOutDir: true,
    // chunkSizeWarningLimit: 1500,
    rollupOptions: {
      // 查看打包后的体积
      plugins: [visualizer()],
      output: {
        // 最小化拆分包
        manualChunks(id) {
          if (id.includes("node_modules")) {
            return id.toString().split("node_modules/")[1].split("/")[0].toString()
          }
        },
        // 用于从入口点创建的块的打包输出格式[name]表示文件名,[hash]表示该文件内容hash值
        entryFileNames: 'js/[name].[hash].js',
        // 用于命名代码拆分时创建的共享块的输出命名
        // chunkFileNames: 'js/[name].[hash].js',
        // 用于输出静态资源的命名，[ext]表示文件扩展名
        // assetFileNames: '[ext]/[name].[hash].[ext]',
        // 拆分js到模块文件夹
        chunkFileNames: (chunkInfo) => {
          const facadeModuleId = chunkInfo.facadeModuleId ? chunkInfo.facadeModuleId.split('/') : [];
          const fileName = facadeModuleId[facadeModuleId.length - 2] || '[name]';
          return `js/${fileName}/[name].[hash].js`;
        },
      }
    },
    minify: 'terser',
    terserOptions: {
      compress: {
        //生产环境时移除console
        // drop_console: true,
        drop_debugger: true,
      },
    },
  }
})

